<template>
  <commonDrawer
    :title="drawerName"
    :drawer="drawerShow"
    :size="480"
    :isShowMoreBtn="true"
    @closeDraw="closeDraw"
    @cancelFun="closeDraw"
    @save="save"
  >
    <template slot="column">
      <div v-if="formData.status === 3" class="no-pass">
        <p><i class="el-icon-error"></i>未通过原因:</p>
        <p class="cont">
          {{ this.formData.reason }}
        </p>
      </div>
      <el-form
        ref="form"
        :model="formData"
        label-position="top"
        :rules="rules"
        size="small"
      >
        <el-form-item label="签名" prop="content">
          <el-input
            :maxlength="8"
            :minlength="2"
            placeholder="至少2个字"
            show-word-limit
            clearable
            v-model="formData.content"
          ></el-input>
        </el-form-item>
        <p class="warn"><i class="el-icon-warning"></i>小贴士</p>
        <p class="tip-cont">
          签名内容为短信发送的真实应用名称、网站名称、公司名称或商标名称；<br />
          若涉及到第三方权益必须获得第三方真实授权；<br />
          不支持如 “客户服务”、“友情提醒”等国语宽泛内容；<br />
          无需添加【】、（）、[]符号，签名发送会自带【】符号，避免重复；
        </p>
        <el-form-item label="签名用途" prop="purpose">
          <el-radio-group v-model="formData.purpose" @change="handlePurpose">
            <el-radio :label="1"> 自用 </el-radio>
            <el-radio :label="2"> 他用 </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-show="formData.purpose === 2"
          prop="authFile"
          :rules="
            formData.purpose === 2 ? rules.authFile : [{ required: false }]
          "
        >
          <span slot="label">
            授权委托书
            <el-tooltip
              content="如果签名用途为他用时，还需上传证明文件或授权委托书"
              placement="top"
            >
              <i
                style="
                  font-size: 12px;
                  color: #b3b9c7;
                  padding-right: 6px;
                  cursor: pointer;
                "
                class="V7_iconfont V7_iconV7tubiao_bangzhu-42"
              ></i>
            </el-tooltip>
          </span>
          <Upload
            ref="uploadFile"
            :multiple="true"
            acceptType=".rar, .zip, .doc, .docx, .pdf, .jpg, .jpeg, .png"
            :limitNum="1"
            btnName="上传文件"
            :limitSize="false"
            :customUploadBtn="true"
            :fileList="formData.fileList"
            :disable="disable"
            @uploadSuccess="uploadSuccess"
            @uploadDelete="uploadDelete"
            @beforeUpload="beforeUpload"
            :class="{ 'dis-btn': disable }"
          >
            <div slot="uploadBtn" class="upload-btn">
              <img src="../../../assets/img/upload.png" alt="" />
              <p class="upload-word">点击上传</p>
            </div>
          </Upload>
          <p class="file-type">
            支持扩展名：.rar .zip .doc .docx .pdf .jpg .jpeg .png
          </p>
        </el-form-item>
      </el-form>
    </template>
  </commonDrawer>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import Upload from '@/components/globalTool/upload/index.vue'
import { commonAction } from '@/utils/common'
import commonDrawer from '@/components/globalTool/resizeDrawer/drawer.vue'
import { v4 as uuidv4 } from 'uuid'
import { CommonModule } from '@/store/modules/common'
@Component({
  name: 'addOrEditAutograph',
  components: {
    Upload,
    commonDrawer
  }
})
export default class CustomerTemplateSetting extends Vue {
  [x: string]: any
  @Ref() private readonly uploadFile
  private type: any = ''

  private drawerName: any = ''

  private drawerShow: boolean = false

  private disable: boolean = false

  public formData: any = {
    content: '',
    purpose: 1,
    proxyFile: '',
    proxyFileName: '',
    status: 1
  }

  private rules: any = {
    content: [{ required: true, validator: this.validateName, trigger: 'blur' }],
    purpose: [{ required: true, message: '请选择签名用途', trigger: 'change' }],
    authFile: [{ required: true, validator: this.validateFile, trigger: 'change' }]
  }

  get getCurAgent () {
    return (CommonModule as any).session.user._id || ''
  }

  get getAccountId () {
    return (CommonModule as any).session.user.accountId || ''
  }

  private validateName (rule, value, callback) {
    if (value.length < 2 || /^\s*$/g.test(value)) {
      callback(new Error('签名不能为空且最小长度为2'))
    } else {
      callback()
    }
  }

  private handlePurpose (val: any) {
    if (val === 1) {
      this.$nextTick(() => {
        (this.$refs.uploadFile as any).attachs = []; // 自用时清空委托书
        this.formData.proxyFile = ''
        this.formData.proxyFileName = ''
      })
    }
  }

  private beforeUpload () {
    this.disable = true // 文件开始上传禁止点击上传按钮
  }

  private validateFile (rule, value, callback) {
    if (this.formData.proxyFile) {
      callback()
    } else {
      callback(new Error('请添加授权委托书'))
    }
  }

  private uploadSuccess (files: any) {
    this.disable = false;
    (this.$refs as any).form.clearValidate(['authFile'])
    if (files && files.length) {
      this.formData.proxyFile = files[0].id
      this.formData.proxyFileName = files[0].name
    }
  }

  private uploadDelete (files: any) {
    if (files && !files.length) {
      this.formData.proxyFile = ''
      this.formData.proxyFileName = ''
    }
  }

  public openDrawer (type: any, row?: any) {
    this.type = type
    this.drawerShow = true
    this.drawerName = type === 'add' ? '创建签名' : '编辑签名'
    if (type === 'edit' && !row.proxyFile) { // 编辑时不存在文件路径清空下文件
      this.formData.proxyFile = ''
      this.formData.proxyFileName = ''
      this.formData.fileList = []
      this.$nextTick(() => {
        (this.$refs.uploadFile as any).attachs = []; // 自用时清空委托书
      })
    }
  }

  public clearData () {
    this.formData = {
      content: '',
      purpose: 1,
      proxyFile: '',
      proxyFileName: '',
      status: 1
    }
    this.disable = false;
    this.$nextTick(() => {
      (this.$refs.uploadFile as any).attachs = []; // 自用时清空委托书
    })
  }

  private getUUID () {
    return uuidv4().replace(/-/g, '')
  }

  private save () {
    (this.$refs as any).form.validate(valid => {
      if (valid) {
        const { content, purpose, proxyFile, proxyFileName, id } = this.formData
        const sendData = {
          requestId: this.getUUID(),
          action: 'MANAGER_SIGN_MODIFY',
          param: {
            content,
            purpose,
            proxyFile,
            proxyFileName,
            id,
            status: 1,
            displayName: this.formData.content, // 签名别名因后端接口限制必填
            customer: this.getAccountId,
            operator: this.getCurAgent
          }
        }
        const params = {
          url: '/sms-api/sms/manager/sign/data',
          method: 'POST',
          data: sendData
        }
        commonAction(params).then(res => {
          if (res.code === '0000200') {
            this.$message.success(`${this.type === 'add' ? '创建' : '更新'}成功`)
            this.drawerShow = false
            this.$emit('updateAutographList')
          }
        })
      }
    })
  }

  private closeDraw () {
    this.drawerShow = false
  }
}
</script>
<style lang="stylus" scoped>
.dis-btn
  >>> .el-upload
    cursor not-allowed
.el-form--label-top
  >>>.el-form-item__label
    display inline
.upload-btn
  width 100px
  height 100px
  background #FFFFFF
  border 1px dashed #E7E9ED
  border-radius 4px
  text-align center
  padding-top 10px
  img
    width 50px
    height auto
  .upload-word
    color #303753
    font-size 12px
    margin-top -6px
.warn
  margin-bottom 4px
  font-weight 600
  color #303753
  i
    color #008BEE
    font-size 14px
    margin-right 6px
.tip-cont
  color #767E91
  line-height 20px
  margin 0 0 10px 8px
.file-type
  color #999
  font-size 10px
.no-pass
  padding 12px 18px 12px 12px
  background #FFFBE6
  border-radius 4px
  color #303753
  font-weight 600
  font-family PingFang SC
  .cont
    margin-left 20px
  i
    margin-right 6px
    font-size 14px
    color #FAAD14
</style>
